package registration;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import swim.sessionbeans.RegistrazioneLocal;

/**
 * Gestisce l'inserimento di un nuovo utente
 */

public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB(mappedName = "Registrazione/remote")
	private RegistrazioneLocal registrazione;

	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 10000 * 1024;
	private int maxMemSize = 10000 * 1024;
	private File file;
	private String path = System.getProperty("user.dir");
	private String step;
	private String fileName;

	private String user;
	private String nome;
	private String cognome;
	private String password;
	private String email;
	private String telefono;
	private String citta;
	private String descrizione;
	private Boolean foto;

	public void init() {
		// Get the file location where it would be stored.
		filePath = path + "/img/";
	}

	public RegistrationServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String macroarea = request.getParameter("macroarea");
		step = request.getParameter("step");

		if (step.equals("3")) {

			List<String> abilitaList = this.registrazione
					.getAbilitaList(macroarea);

			//List<String> abilitaIdList = new ArrayList<String>();
			//List<String> abilitaNomeList = new ArrayList<String>();

			//for (Abilita a : abilitaList) {
				//abilitaIdList.add(a.getId().toString());
			//}

			//for (Abilita a : abilitaList) {
				//abilitaNomeList.add(a.getNome());
			//}

			request.setAttribute("macroarea", macroarea);
			request.setAttribute("abilitaList", abilitaList);
			//request.setAttribute("abilitaIdList", abilitaNomeList);

			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/home-registrazione4.jsp");
			dispatcher.forward(request, response);
		}

	}

	/**
	 * Inserisce nel sistema un nuovo utente utilizzando i parametri inseriti
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String esito;

		step = (String) request.getParameter("step");

		if (step.equals("1")) {

			try {

				user = request.getParameter("user");
				nome = request.getParameter("nome");
				cognome = request.getParameter("cognome");
				password = request.getParameter("password");
				email = request.getParameter("email");
				telefono = request.getParameter("telefono");
				citta = request.getParameter("citta");
				descrizione = request.getParameter("descrizione");

				this.registrazione.step1(user.trim(), password.trim(), nome.trim(), cognome.trim(),
						telefono.trim(), email.trim(), citta.trim(), descrizione.trim());

			} catch (Exception e) {
				e.printStackTrace();
				out = response.getWriter();
				out.print("<h1>Inserimento fallito!! - errore! </h1>");
				out.print("<br><br><a href=\"/home-registrazione.html\"><b>Torna alla pagina di registrazione</b></a><br><br>");
			}

			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/home-registrazione2.jsp");
			dispatcher.forward(request, response);

		} else if (step.equals("2")) {

			// Check that we have a file upload request
			isMultipart = ServletFileUpload.isMultipartContent(request);

			if (!isMultipart) {
				esito = "Nessun file caricato";
				return;
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			// maximum size that will be stored in memory
			factory.setSizeThreshold(maxMemSize);
			// Location to save data that is larger than maxMemSize.
			factory.setRepository(new File(path + "/temp/"));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// maximum file size to be uploaded.
			upload.setSizeMax(maxFileSize);

			try {
				// Parse the request to get file items.
				List fileItems = upload.parseRequest(request);

				// Process the uploaded file items
				Iterator i = fileItems.iterator();

				while (i.hasNext()) {
					FileItem fi = (FileItem) i.next();
					if (!fi.isFormField()) {
						// Get the uploaded file parameters
						String fieldName = fi.getFieldName();
						fileName = fi.getName();
						String contentType = fi.getContentType();
						boolean isInMemory = fi.isInMemory();
						long sizeInBytes = fi.getSize();
						// Write the file
						String completePath;
						if (fileName.lastIndexOf("\\") >= 0) {
							completePath = filePath
									+ fileName.substring(fileName
											.lastIndexOf("\\"));
						} else {
							completePath = filePath
									+ fileName.substring(fileName
											.lastIndexOf("\\") + 1);
						}
						
						file = new File(completePath);
						fi.write(file);
						BufferedImage bsrc = ImageIO.read(file);
						int width;
						int height;
						double r_width=150;
						double r_height=220;
						double oldWidth = bsrc.getWidth(); 
						double oldHeight = bsrc.getHeight();
						if ((oldWidth/oldHeight) > (r_width/r_height)) {  // Caso 1 
						    width = (int) r_width; 
						    height = (int) ((width/oldWidth) * oldHeight); 
						} 
						else {  // Caso 2 
						    height = (int) r_height; 
						    width = (int) ((height/oldHeight) * oldWidth); 
						}
							   
							   BufferedImage bdest =
							      new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
							   Graphics2D g = bdest.createGraphics();
							   RenderingHints rh = new RenderingHints(
							             RenderingHints.KEY_ANTIALIASING,
							             RenderingHints.VALUE_ANTIALIAS_ON);
							   g.setRenderingHints(rh);
							   AffineTransform at =
							      AffineTransform.getScaleInstance((double)width/bsrc.getWidth(),
							          (double)height/bsrc.getHeight());
							   g.drawRenderedImage(bsrc,at);
							   ImageIO.write(bdest,"JPG",new File(completePath));
							  
						
						

						esito = "File caricato:" + fileName;
						foto = true;
						registrazione.step2(fileName.trim(),foto);
					}
				}
			} catch (Exception ex) {
				System.out.println(ex);
			}

			List<String> macroareaList = this.registrazione.getMacroareaList();
			request.setAttribute("macroareaList", macroareaList);

			for (String s : macroareaList) {
				System.out.print("Queste sono le macroaree:" + s);
			}

			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/home-registrazione3.jsp");
			dispatcher.forward(request, response);

		} else if (step.equals("4")) {

			String[] abilitaArray = request.getParameterValues("abilitaArray");

			for (String r : Arrays.asList(abilitaArray)) {
				System.out.print("Array delle stringhe passate" + r);
			}

			Long id = registrazione.step3(Arrays.asList(abilitaArray));
			boolean isOK = false;

			if (id != -1) {
				esito = "<h1>L'utente ha effettuato la registrazione correttamente</h1>";
				isOK = true;
			} else
				esito = "<h1>Login fallito!</h1>";

			request.setAttribute("esito", esito);
			request.setAttribute("isOK", isOK);
			
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/home-registrazione5.jsp");
			dispatcher.forward(request, response);

		}

	}

}
